
package com.xebest.web.controller.logistics;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.xebest.api.dto.XeSysMsgRecordDTO;
import com.xebest.api.dto.XeSysMsgSendDTO;
import com.xebest.api.dto.resdto.XeSysMsgRecordResDTO;
import com.xebest.api.service.XeSysMsgApiService;
import com.xebest.api.util.OpertorLogUtil;
import com.xebest.common.base.controller.BASEMessage;
import com.xebest.common.base.controller.BaseController;
import com.xebest.common.base.controller.BaseResponse;
import com.xebest.common.enums.logtype.ErpLogTypeEnum;
import com.xebest.common.util.HttpClientUtil;
import com.xebest.common.util.RequestUtil;
import com.xebest.common.util.XeBaseUtil;
import com.xebest.config.SmsConfig;
import com.xebest.constant.XeConstans;
import com.xebest.constant.XeSmsConstans;
import com.xebest.util.SmsConstants;
import com.xebest.util.SysSetBeanUtils;
import com.xebest.util.XeVenImportExcelUtil;
import com.xebest.util.msg.XeVenLogisticsMsg;
import com.xebest.web.form.XeVenCarForm;
import com.xebest.web.form.XeVenCarSendForm;
import com.xebest.web.form.XeVenOrderLogisticsForm;
import com.xebest.web.model.XeVenCarEntity;
import com.xebest.web.model.XeVenOrderLogisticsDetail;
import com.xebest.web.model.base.XePageInfo;
import com.xebest.web.service.WeChatVenOrderLogisticsService;
import com.xebest.web.service.XeLogisticsCarService;
import com.xebest.web.service.XeVenOrderLogisticsService;
import com.xebest.web.service.XeVenOrderService;
import com.xebest.web.view.ErpUserInfo;
import com.xebest.web.view.XeVenOrderLogisticsView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 物流Controller
 *
 * @author 赵盼飞
 */
@RestController
@RequestMapping("logistics")
public class XeVenOrderLogisticsController extends BaseController {

	/**
	 * 物流Service
	 */
	@Autowired
	private XeVenOrderLogisticsService logisticsService;
	/**
	 * 订单操作service
	 */
	@Autowired
	private XeVenOrderService xeVenOrderService;

	@Autowired
	private WeChatVenOrderLogisticsService weChatVenOrderLogisticsService;

	@Autowired
	private SmsConfig smsConfig;

	@Autowired
	private XeLogisticsCarService xeLogisticsCarService;

	@Autowired
	private XeSysMsgApiService xeSysMsgApiService;// 消消乐发送通知业务类

	private static final Logger log = LoggerFactory.getLogger(XeVenOrderLogisticsController.class);// 日志记录类

	/**
	 * 物流单查询
	 *
	 * @author 赵盼飞
	 */
	@RequestMapping("queryOrderLogisticsList")
	public @ResponseBody BaseResponse queryOrderLogisticsList(@RequestBody XeVenOrderLogisticsForm form) {

		try {
			XePageInfo<XeVenOrderLogisticsView> xePageInfo;
			PageHelper.startPage(form.getPageNum(), form.getPageSize(), true);
			// 1.获取userCode
			ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
			Map<String, Object> map = new HashMap<String, Object>();
			form.setUserCode(userInfo.getUserCode());
			// 权限使用
			if (XeConstans._XE_TWO == userInfo.getAdminFlag()) {
				if (!StringUtils.isEmpty(userInfo.getRoleIds())) {
					form.setRoleId(userInfo.getRoleIds().split(","));
				} else {
					form.setRoleId(null);
				}
				form.setAdmin("noAdmin");
			} else {
				form.setAdmin(null);
			}
			// 2.查询列表数据
			List<XeVenOrderLogisticsView> orderLogisticsList = this.logisticsService.queryOrderLogisticsList(form);
			xePageInfo = new XePageInfo<XeVenOrderLogisticsView>(orderLogisticsList);
			// 3.返回分页信息
			map.put("orderLogisticsList", orderLogisticsList);
			map.put("xePageInfo", xePageInfo);
			return sendAjaxOK(map);
		} catch (Exception e) {
			log.error("物流单查询列表接口异常：{}", e);
			return sendAjaxError();
		}

	}

	/**
	 * 物流进度
	 *
	 * @author 赵盼飞
	 */
	@RequestMapping("queryOrderLogisticsDetail")
	public @ResponseBody BaseResponse queryOrderLogisticsDetail(@RequestBody XeVenOrderLogisticsForm form) {

		try {
			// 1.验证参数
			if (StringUtils.isEmpty(form.getOrderId())) {
				return sendAjaxError(BASEMessage.PARAM_ERROR);
			}
			ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
			form.setUserCode(userInfo.getUserCode());
			// 2.查询列表数据
			List<XeVenOrderLogisticsDetail> orderLogisticsDetailList = this.logisticsService
					.selectLogisticsDetailList(form);
			// 3.返回分页信息
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("orderLogisticsDetail", orderLogisticsDetailList);
			return sendAjaxOK(map);
		} catch (Exception e) {
			log.error("物流进度接口异常：{}", e);
			return sendAjaxError();
		}

	}

	/**
	 * 客户信息
	 *
	 * @author 赵盼飞
	 */
	@RequestMapping("queryCustomerLogisticsDetail")
	public @ResponseBody BaseResponse queryCustomerLogisticsDetail(@RequestBody XeVenOrderLogisticsForm form) {

		try {
			// 1.验证参数
			if (StringUtils.isEmpty(form.getLogtsCode())) {
				return sendAjaxError(BASEMessage.PARAM_ERROR);
			}
			ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
			form.setUserCode(userInfo.getUserCode());
			// 2.查询列表数据
			Map<String, Object> customerLogisticsDetail = this.logisticsService.queryCustomerLogisticsDetail(form);
			// 3.返回分页信息
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("customerLogisticsDetail", customerLogisticsDetail);
			return sendAjaxOK(map);
		} catch (Exception e) {
			log.error("物流单查询客户信息接口异常：{}", e);
			return sendAjaxError();
		}

	}

	/**
	 * 商品信息
	 *
	 * @author 赵盼飞
	 */
	@RequestMapping("queryGoodsLogisticsDetail")
	public @ResponseBody BaseResponse queryGoodsLogisticsDetail(@RequestBody XeVenOrderLogisticsForm form) {

		try {
			// 1.验证参数
			if (StringUtils.isEmpty(form.getOrderId())) {
				return sendAjaxError(BASEMessage.PARAM_ERROR);
			}
			ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
			form.setUserCode(userInfo.getUserCode());
			// 2.查询列表数据
			Map<String, Object> goodsLogisticsDetail = this.xeVenOrderService.queryOrderInfoDetail(form.getOrderId(),
					userInfo);
			// 3.返回分页信息
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("goodsLogisticsDetail", goodsLogisticsDetail);
			return sendAjaxOK(map);
		} catch (Exception e) {
			log.error("物流单查询商品信息接口异常：{}", e);
			return sendAjaxError();
		}

	}

	/**
	 * 物流单查询备注信息
	 *
	 * @author 赵盼飞
	 */
	@RequestMapping("queryRemarkLogisticsDetail")
	public @ResponseBody BaseResponse queryRemarkLogisticsDetail(@RequestBody XeVenOrderLogisticsForm form) {

		try {
			// 1.验证参数
			if (StringUtils.isEmpty(form.getLogtsCode())) {
				return sendAjaxError(BASEMessage.PARAM_ERROR);
			}
			ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
			form.setUserCode(userInfo.getUserCode());
			// 2.查询列表数据
			Map<String, Object> remarkLogisticsDetail = this.logisticsService.queryRemarkLogisticsDetail(form);
			// 3.返回分页信息
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("remarkLogistics", remarkLogisticsDetail);
			return sendAjaxOK(map);
		} catch (Exception e) {
			log.error("物流单查询备注信息接口异常：{}", e);
			return sendAjaxError();
		}

	}

	/**
	 * 物流派车列表查询
	 *
	 * @author 赵盼飞
	 */
	@RequestMapping("querySendCarList")
	public @ResponseBody BaseResponse querySendCarList(@RequestBody XeVenOrderLogisticsForm form) {

		try {
			XePageInfo<XeVenOrderLogisticsView> xePageInfo;
			PageHelper.startPage(form.getPageNum(), form.getPageSize(), true);
			// 1.获取userCode
			ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
			Map<String, Object> map = new HashMap<String, Object>();
			form.setUserCode(userInfo.getUserCode());
			// 权限使用
			if (XeConstans._XE_TWO == userInfo.getAdminFlag()) {
				if (!StringUtils.isEmpty(userInfo.getRoleIds())) {
					form.setRoleId(userInfo.getRoleIds().split(","));
				} else {
					form.setRoleId(null);
				}
				form.setAdmin("noAdmin");
			} else {
				form.setAdmin(null);
			}
			// 2.查询列表数据
			List<XeVenOrderLogisticsView> sendCarList = this.logisticsService.querySendCarList(form);
			xePageInfo = new XePageInfo<XeVenOrderLogisticsView>(sendCarList);
			// 3.返回分页信息
			map.put("sendCarList", sendCarList);
			map.put("xePageInfo", xePageInfo);
			return sendAjaxOK(map);
		} catch (Exception e) {
			log.error("物流单查询列表接口异常：{}", e);
			return sendAjaxError();
		}

	}

	/**
	 * 跳转到派车页面
	 *
	 * @author 赵盼飞
	 */
	@RequestMapping("toSendCarPage")
	public @ResponseBody BaseResponse toSendCarPage(@RequestBody XeVenOrderLogisticsForm form,
			HttpServletRequest request) {

		try {
			// 1.验证参数
			if (StringUtils.isEmpty(form.getLogtsCode())) {
				return sendAjaxError(BASEMessage.PARAM_ERROR);
			}
			ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
			form.setUserCode(userInfo.getUserCode());
			// 2.查询列表数据
			Map<String, Object> sendCarLogistics = this.logisticsService.querySendCarLogisticsByLogtsCode(form);
			// 返回的默认车辆信息
			Map<String, Object> latelySendCar = new HashMap<String, Object>();
			if (null != sendCarLogistics && !StringUtils.isEmpty(sendCarLogistics.get("shipCarDes"))) {
				if (!StringUtils.isEmpty(sendCarLogistics.get("shipCarId"))) {
					latelySendCar = logisticsService
							.queryCarInfoByCarId(Integer.valueOf(sendCarLogistics.get("shipCarId").toString()));
				}
				// 4.返回信息
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("sendCarLogistics", sendCarLogistics);
				map.put("latelySendCar", latelySendCar);
				return sendAjaxOK(map);
			} else {
				// 3.获取派车页所需数据根据发货，收货区域，usercode获取最近一张物流单的未删除承运车辆
				Map<String, Object> paraMap = new HashMap<String, Object>();
				paraMap.put("userCode", userInfo.getUserCode());
				paraMap.put("caProvinceId", sendCarLogistics.get("caProvinceId"));
				paraMap.put("caCityId", sendCarLogistics.get("caCityId"));
				paraMap.put("caAreaId", sendCarLogistics.get("caAreaId"));
				paraMap.put("provinceId", sendCarLogistics.get("provinceId"));
				paraMap.put("cityId", sendCarLogistics.get("cityId"));
				paraMap.put("areaId", sendCarLogistics.get("areaId"));
				latelySendCar = this.logisticsService.querylatelySendCarLogistics(paraMap);

				// 4.返回信息
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("sendCarLogistics", sendCarLogistics);
				map.put("latelySendCar", latelySendCar);
				return sendAjaxOK(map);
			}
		} catch (Exception e) {
			log.error("跳转到派车页面接口异常：{}", e);
			return sendAjaxError();
		}

	}

	/**
	 * 保存派车信息
	 *
	 * @author 赵盼飞
	 */
	@RequestMapping("saveSendCarInfo")
	public @ResponseBody BaseResponse saveSendCarInfo(@RequestBody XeVenCarSendForm form, HttpServletRequest request) {

		try {
			// 1.验证参数
			if (StringUtils.isEmpty(form.getLoadAddr()) || StringUtils.isEmpty(form.getLoadTime())
					|| StringUtils.isEmpty(form.getUnloadAddr()) || StringUtils.isEmpty(form.getUnloadTime())
					|| StringUtils.isEmpty(form.getCarId()) || StringUtils.isEmpty(form.getLogtCode())
					|| StringUtils.isEmpty(form.getProvinceId()) || StringUtils.isEmpty(form.getCityId())
					|| StringUtils.isEmpty(form.getAreaId()) || StringUtils.isEmpty(form.getCaProvinceId())
					|| StringUtils.isEmpty(form.getCaCityId()) || StringUtils.isEmpty(form.getCaAreaId())
					|| StringUtils.isEmpty(form.getCarPlateNum()) || StringUtils.isEmpty(form.getMobilePhone())
					|| StringUtils.isEmpty(form.getUpFlag())) {
				return sendAjaxError(BASEMessage.PARAM_ERROR);
			}
			log.info("保存派车信息:接口传入参数：{}", JSON.toJSONString(form));
			/*
			 * boolean b = isRepeatSubmit(request,form.getToken());//判断用户是否是重复提交
			 * if (b == true) { return sendAjaxError("无需重复提交！"); }
			 */
			// request.getSession().removeAttribute("token");//移除session中的token
			ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
			form.setUserCode(userInfo.getUserCode());
			form.setCreateUser(userInfo.getLoginName());
			// 验证订单状态
			Map<String, Object> orderStateMap = logisticsService.queryOrderStateByLogtCode(form.getLogtCode());
			if (orderStateMap.get("orderStatus").toString().equals("1")
					|| orderStateMap.get("orderStatus").toString().equals("2")) {
				return sendAjaxError(BASEMessage.PARAM_ERROR, XeVenLogisticsMsg.ORDER_SEND_FIN);
			} else if (orderStateMap.get("orderStatus").toString().equals("4")) {
				return sendAjaxError(BASEMessage.PARAM_ERROR, XeVenLogisticsMsg.ORDER_CANCEL);
			}
			// 验证车辆路线
			Map<String, Object> carLinesMap = logisticsService.queryCarLinesByCarId(form.getCarId());
			// 若仓库所在地到收货区域不是承运车辆的承运线路，则新增承运线路
			int res = 0;
			if (null != carLinesMap) {
				String sendArea = form.getProvinceId() + "" + form.getCityId() + "" + form.getAreaId();
				String receiptArea = form.getCaProvinceId() + "" + form.getCaCityId() + "" + form.getCaAreaId();
				if (!((carLinesMap.get("sendArea").toString().contains(sendArea)
						|| carLinesMap.get("sendArea").toString().contains(receiptArea))
						& (carLinesMap.get("receiptArea").toString().contains(sendArea)
								|| carLinesMap.get("receiptArea").toString().contains(receiptArea)))) {
					res = logisticsService.saveCarLines(form);
				}
			} else {
				res = logisticsService.saveCarLines(form);
			}
			// 2.保存数据
			res = this.logisticsService.saveSendCarInfo(form);
			// 派车成功向采购商发送短信
			StringBuffer sb = new StringBuffer();
			sb.append("mobileNO=").append(orderStateMap.get("loginAccount")).append("&merchantKey=")
					.append(smsConfig.getMerchantKey());
			String verifyString = XeBaseUtil.baseUtil.getKeyedDigest(sb.toString(), SmsConstants.MSG_MERCHANT_KEY);
			JSONObject smsJson = new JSONObject();
			smsJson.put("mobileNO", orderStateMap.get("loginAccount"));
			smsJson.put("sendSource", "派车成功向采购商发送短信");
			smsJson.put("smsNO", XeSmsConstans.XE_ERP_SENDCAR_PUR_SEND_MSG);
			smsJson.put("verifyString", verifyString);
			smsJson.put("orderNum", orderStateMap.get("orderId"));
			smsJson.put("carPlateNum", form.getCarPlateNum());
			smsJson.put("contactPerson", form.getContactPerson());
			smsJson.put("mobilePhone", form.getMobilePhone());
			log.info("派车成功向采购商发送短信参数：--->" + JSON.toJSONString(smsJson));
			HttpClientUtil.postJSON(smsConfig.getSmsUrl(), smsJson);
			// 派车成功向消消乐客户经理发送通知
			List<XeSysMsgSendDTO> xeSysMsgSendDTOList = new ArrayList<>();
			XeSysMsgRecordDTO msgRecordDTO = new XeSysMsgRecordDTO();
			XeSysMsgSendDTO sendDTO = new XeSysMsgSendDTO();
			sendDTO.setMsgNumber(XeSmsConstans.XE_ERP_SENDCAR_SALESMAN_SEND_MSG_NOTICE);
			if (!StringUtils.isEmpty(orderStateMap.get("salesmanPhone"))) {
				sendDTO.setMobile(orderStateMap.get("salesmanPhone").toString());
			}
			if (!StringUtils.isEmpty(orderStateMap.get("salesmanId"))) {
				sendDTO.setUserId(orderStateMap.get("salesmanId").toString());
			}
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("userName", orderStateMap.get("userName") == null ? "" : orderStateMap.get("userName"));
			jsonObject.put("loginAccount", orderStateMap.get("loginAccount"));
			jsonObject.put("orderNum", orderStateMap.get("orderId"));
			jsonObject.put("carNum", form.getCarPlateNum());
			jsonObject.put("linkMan", form.getContactPerson() == null ? "" : form.getContactPerson());
			jsonObject.put("contactNum", form.getMobilePhone());
			sendDTO.setMsgContentParam(jsonObject);
			JSONObject jsonObjectJump = new JSONObject();
			jsonObjectJump.put("subOrderId", orderStateMap.get("orderId"));
			jsonObjectJump.put("userId", orderStateMap.get("userId"));// 业务员标识
			jsonObjectJump.put("orderPlat", orderStateMap.get("orderSource"));
			sendDTO.setJumpData(jsonObjectJump);// 跳转参数设置
			xeSysMsgSendDTOList.add(sendDTO);
			msgRecordDTO.setXeSysMsgSendDTOList(xeSysMsgSendDTOList);
			log.info("派车成功向客户经理消消乐推送通知入参：--->" + JSON.toJSONString(msgRecordDTO));
			XeSysMsgRecordResDTO msgRecordResDTO = xeSysMsgApiService.sendMsgRecords(msgRecordDTO);
			log.info("派车成功向客户经理消消乐推送通知返回结果：--->" + JSON.toJSONString(msgRecordResDTO));

			Map<String, Object> map = new HashMap<String, Object>();
			if (res > 0) {
				insertLogisticsMqLog(ErpLogTypeEnum.erpFinLogisticsAsendCar.getValue(), form.getLogtCode(),
						"PC端生意管家派车。物流单号：" + form.getLogtCode() + "。承运车辆：" + form.getCarPlateNum() + "。装车点："
								+ form.getLoadAddr() + "。预计装车时间" + form.getLoadTime() + "。卸货点：" + form.getUnloadAddr()
								+ "。预计送达时间" + form.getUnloadTime() + "。");
				// 3.返回信息
				map.put("info", "派车成功！");
			} else {
				map.put("info", "保存失败，请稍后重试！");
			}

			// 向司机发送短信通知
			String logtsCode = form.getLogtCode();
			String orderId = (String) orderStateMap.get("orderId");
			String userCode = form.getUserCode();
			String mobilePhone = form.getMobilePhone();

			log.info("-----PC端单个派车向司机发短信通知--------开始");
			weChatVenOrderLogisticsService.sendMsgToDriver(logtsCode, orderId, userCode, mobilePhone);
			log.info("-----PC端单个派车向司机发短信通知--------结束");

			return sendAjaxOK(map);
		} catch (Exception e) {
			log.error("保存派车信息接口异常：{}", e);
			return sendAjaxError();
		}

	}
	/**
	 * 保存快递信息
	 *
	 * @author 袁世林
	 */
	@RequestMapping("saveSendExpressInfo")
	public @ResponseBody BaseResponse saveSendExpressInfo(@RequestBody XeVenCarSendForm form) {

		try {
			// 1.验证参数
			if (StringUtils.isEmpty(form.getExpressName()) || StringUtils.isEmpty(form.getExpressNumber())
					|| StringUtils.isEmpty(form.getLogtCode()) || StringUtils.isEmpty(form.getUpFlag())) {
				return sendAjaxError(BASEMessage.PARAM_ERROR);
			}
			log.info("保存派车信息:接口传入参数：{}", JSON.toJSONString(form));
			ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
			form.setUserCode(userInfo.getUserCode());
			form.setCreateUser(userInfo.getLoginName());
			// 验证订单状态
			Map<String, Object> orderStateMap = logisticsService.queryOrderStateByLogtCode(form.getLogtCode());
			if (orderStateMap.get("orderStatus").toString().equals("1")
					|| orderStateMap.get("orderStatus").toString().equals("2")) {
				return sendAjaxError(BASEMessage.PARAM_ERROR, XeVenLogisticsMsg.ORDER_SEND_FIN);
			} else if (orderStateMap.get("orderStatus").toString().equals("4")) {
				return sendAjaxError(BASEMessage.PARAM_ERROR, XeVenLogisticsMsg.ORDER_CANCEL);
			}
			// 若仓库所在地到收货区域不是承运车辆的承运线路，则新增承运线路
			int res = 0;
			// 2.保存数据
			res = this.logisticsService.saveSendCarInfo(form);
			// 派车成功向采购商发送短信
			StringBuffer sb = new StringBuffer();
			sb.append("mobileNO=").append(orderStateMap.get("loginAccount")).append("&merchantKey=")
					.append(smsConfig.getMerchantKey());
			String verifyString = XeBaseUtil.baseUtil.getKeyedDigest(sb.toString(), SmsConstants.MSG_MERCHANT_KEY);
			JSONObject smsJson = new JSONObject();
			smsJson.put("mobileNO", orderStateMap.get("loginAccount"));
			smsJson.put("sendSource", "派车成功向采购商发送短信");
			smsJson.put("smsNO", XeSmsConstans.XE_ERP_SENDCAR_PUR_SEND_MSG);
			smsJson.put("verifyString", verifyString);
			smsJson.put("orderNum", orderStateMap.get("orderId"));
			smsJson.put("carPlateNum", form.getCarPlateNum());
			smsJson.put("contactPerson", form.getContactPerson());
			smsJson.put("mobilePhone", form.getMobilePhone());
			log.info("派车成功向采购商发送短信参数：--->" + JSON.toJSONString(smsJson));
			HttpClientUtil.postJSON(smsConfig.getSmsUrl(), smsJson);
			// 派车成功向消消乐客户经理发送通知
			List<XeSysMsgSendDTO> xeSysMsgSendDTOList = new ArrayList<>();
			XeSysMsgRecordDTO msgRecordDTO = new XeSysMsgRecordDTO();
			XeSysMsgSendDTO sendDTO = new XeSysMsgSendDTO();
			sendDTO.setMsgNumber(XeSmsConstans.XE_ERP_SENDCAR_SALESMAN_SEND_MSG_NOTICE);
			if (!StringUtils.isEmpty(orderStateMap.get("salesmanPhone"))) {
				sendDTO.setMobile(orderStateMap.get("salesmanPhone").toString());
			}
			if (!StringUtils.isEmpty(orderStateMap.get("salesmanId"))) {
				sendDTO.setUserId(orderStateMap.get("salesmanId").toString());
			}
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("userName", orderStateMap.get("userName") == null ? "" : orderStateMap.get("userName"));
			jsonObject.put("loginAccount", orderStateMap.get("loginAccount"));
			jsonObject.put("orderNum", orderStateMap.get("orderId"));
			jsonObject.put("carNum", form.getCarPlateNum());
			jsonObject.put("linkMan", form.getContactPerson() == null ? "" : form.getContactPerson());
			jsonObject.put("contactNum", form.getMobilePhone());
			sendDTO.setMsgContentParam(jsonObject);
			JSONObject jsonObjectJump = new JSONObject();
			jsonObjectJump.put("subOrderId", orderStateMap.get("orderId"));
			jsonObjectJump.put("userId", orderStateMap.get("userId"));// 业务员标识
			jsonObjectJump.put("orderPlat", orderStateMap.get("orderSource"));
			sendDTO.setJumpData(jsonObjectJump);// 跳转参数设置
			xeSysMsgSendDTOList.add(sendDTO);
			msgRecordDTO.setXeSysMsgSendDTOList(xeSysMsgSendDTOList);
			log.info("派车成功向客户经理消消乐推送通知入参：--->" + JSON.toJSONString(msgRecordDTO));
			XeSysMsgRecordResDTO msgRecordResDTO = xeSysMsgApiService.sendMsgRecords(msgRecordDTO);
			log.info("派车成功向客户经理消消乐推送通知返回结果：--->" + JSON.toJSONString(msgRecordResDTO));

			Map<String, Object> map = new HashMap<String, Object>();
			if (res > 0) {
				insertLogisticsMqLog(ErpLogTypeEnum.erpFinLogisticsAsendCar.getValue(), form.getLogtCode(),
						"PC端生意管家派车。物流单号：" + form.getLogtCode() + "。承运车辆：" + form.getCarPlateNum() + "。装车点："
								+ form.getLoadAddr() + "。预计装车时间" + form.getLoadTime() + "。卸货点：" + form.getUnloadAddr()
								+ "。预计送达时间" + form.getUnloadTime() + "。");
				// 3.返回信息
				map.put("info", "派车成功！");
			} else {
				map.put("info", "保存失败，请稍后重试！");
			}

			// 向司机发送短信通知
			String logtsCode = form.getLogtCode();
			String orderId = (String) orderStateMap.get("orderId");
			String userCode = form.getUserCode();
			String mobilePhone = form.getMobilePhone();

			log.info("-----PC端单个派车向司机发短信通知--------开始");
			weChatVenOrderLogisticsService.sendMsgToDriver(logtsCode, orderId, userCode, mobilePhone);
			log.info("-----PC端单个派车向司机发短信通知--------结束");

			return sendAjaxOK(map);
		} catch (Exception e) {
			log.error("保存派车信息接口异常：{}", e);
			return sendAjaxError();
		}

	}
	/**
	 * 跳转到批量派车页面
	 *
	 * @author 赵盼飞
	 */
	@RequestMapping("toBathSendCarPage")
	public @ResponseBody BaseResponse toBathSendCarPage(@RequestBody XeVenOrderLogisticsForm form,
			HttpServletRequest request) {

		try {
			// 1.验证参数
			if (StringUtils.isEmpty(form.getLogtsCodeArr())) {
				return sendAjaxError(BASEMessage.PARAM_ERROR);
			}
			ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
			form.setUserCode(userInfo.getUserCode());
			// 2.查询列表数据
			List<Map<String, Object>> sendCarLogisticsList = this.logisticsService
					.querySendCarLogisticsByLogtsCodeArr(form);
			// 3.返回信息
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("sendCarLogisticsList", sendCarLogisticsList);
			return sendAjaxOK(map);
		} catch (Exception e) {
			log.error("跳转到批量派车页面接口异常：{}", e);
			return sendAjaxError();
		}

	}

	/**
	 * 保存批量派车信息
	 *
	 * @author 赵盼飞
	 */
	@RequestMapping("saveBathSendCarInfo")
	public @ResponseBody BaseResponse saveBathSendCarInfo(@RequestBody XeVenCarSendForm form,
			HttpServletRequest request) {
		log.info("保存批量派车信息:接口传入参数：{}", JSON.toJSONString(form));
		try {
			// 1.验证参数
			if (form.getLogtCodeArr().length <= 0 || StringUtils.isEmpty(form.getLoadTime())
					|| StringUtils.isEmpty(form.getUnloadAddr()) || StringUtils.isEmpty(form.getUnloadTime())
					|| StringUtils.isEmpty(form.getCarId()) || StringUtils.isEmpty(form.getProvinceId())
					|| StringUtils.isEmpty(form.getCityId()) || StringUtils.isEmpty(form.getAreaId())
					|| StringUtils.isEmpty(form.getCaProvinceId()) || StringUtils.isEmpty(form.getCaCityId())
					|| StringUtils.isEmpty(form.getCaAreaId()) || StringUtils.isEmpty(form.getCarPlateNum())
					|| StringUtils.isEmpty(form.getMobilePhone()) || StringUtils.isEmpty(form.getUpFlag())) {
				return sendAjaxError(BASEMessage.PARAM_ERROR);
			}
			/*
			 * boolean b = isRepeatSubmit(request,form.getToken());//判断用户是否是重复提交
			 * if (b == true) { return sendAjaxError("无需重复提交！"); }
			 */
			// request.getSession().removeAttribute("token");//移除session中的token
			ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
			form.setUserCode(userInfo.getUserCode());
			form.setCreateUser(userInfo.getLoginName());
			// 验证订单状态
			List<Map<String, Object>> orderStateList = logisticsService
					.queryOrderStateByLogtCodeArr(form.getLogtCodeArr());
			for (Map<String, Object> orderStateMap : orderStateList) {
				if (orderStateMap.get("orderStatus").toString().equals("1")
						|| orderStateMap.get("orderStatus").toString().equals("2")) {
					return sendAjaxError(BASEMessage.PARAM_ERROR, XeVenLogisticsMsg.ORDER_SEND_FIN);
				} else if (orderStateMap.get("orderStatus").toString().equals("4")) {
					return sendAjaxError(BASEMessage.PARAM_ERROR, XeVenLogisticsMsg.ORDER_CANCEL);
				}
			}

			// 验证车辆路线
			Map<String, Object> carLinesMap = logisticsService.queryCarLinesByCarId(form.getCarId());
			// 若仓库所在地到收货区域不是承运车辆的承运线路，则新增承运线路
			int res = 0;
			String sendArea = form.getProvinceId() + "" + form.getCityId() + "" + form.getAreaId();
			String receiptArea = form.getCaProvinceId() + "" + form.getCaCityId() + "" + form.getCaAreaId();
			if (!((carLinesMap.get("sendArea").toString().contains(sendArea)
					|| carLinesMap.get("sendArea").toString().contains(receiptArea))
					& (carLinesMap.get("receiptArea").toString().contains(sendArea)
							|| carLinesMap.get("receiptArea").toString().contains(receiptArea)))) {
				res = logisticsService.saveCarLines(form);
			}
			// 2.保存数据
			res = this.logisticsService.saveBathSendCarInfo(form);
			// 3.返回信息
			Map<String, Object> map = new HashMap<String, Object>();
			if (res > 0) {
				// 日志
				insertLogisticsMqLog(ErpLogTypeEnum.erpFinLogisticsBathsendCar.getValue(),
						XeVenImportExcelUtil.arrConversonStr(form.getLogtCodeArr()),
						"PC端生意管家派车。物流单号：" + form.getLogtCode() + "。承运车辆：" + form.getCarPlateNum() + "。装车点："
								+ form.getLoadAddr() + "。预计装车时间" + form.getLoadTime() + "。卸货点：" + form.getUnloadAddr()
								+ "。预计送达时间" + form.getUnloadTime() + "。");

				for (Map<String, Object> mapInfo : orderStateList) {
					// 派车成功向采购商发送短信
					StringBuffer sb = new StringBuffer();
					sb.append("mobileNO=").append(mapInfo.get("loginAccount")).append("&merchantKey=")
							.append(smsConfig.getMerchantKey());
					String verifyString = XeBaseUtil.baseUtil.getKeyedDigest(sb.toString(),
							SmsConstants.MSG_MERCHANT_KEY);
					JSONObject smsJson = new JSONObject();
					smsJson.put("mobileNO", mapInfo.get("loginAccount"));
					smsJson.put("sendSource", "派车成功向采购商发送短信");
					smsJson.put("smsNO", XeSmsConstans.XE_ERP_SENDCAR_PUR_SEND_MSG);
					smsJson.put("verifyString", verifyString);
					smsJson.put("orderNum", mapInfo.get("orderId"));
					smsJson.put("carPlateNum", form.getCarPlateNum());
					smsJson.put("contactPerson", form.getContactPerson());
					smsJson.put("mobilePhone", form.getMobilePhone());
					log.info("批量派车成功向采购商发送短信参数：--->" + JSON.toJSONString(smsJson));
					HttpClientUtil.postJSON(smsConfig.getSmsUrl(), smsJson);
					// 派车成功向消消乐客户经理发送通知
					List<XeSysMsgSendDTO> xeSysMsgSendDTOList = new ArrayList<>();
					XeSysMsgRecordDTO msgRecordDTO = new XeSysMsgRecordDTO();
					XeSysMsgSendDTO sendDTO = new XeSysMsgSendDTO();
					sendDTO.setMsgNumber(XeSmsConstans.XE_ERP_SENDCAR_SALESMAN_SEND_MSG_NOTICE);
					if (!StringUtils.isEmpty(mapInfo.get("salesmanPhone"))) {
						sendDTO.setMobile(mapInfo.get("salesmanPhone").toString());
					}
					if (!StringUtils.isEmpty(mapInfo.get("salesmanId"))) {
						sendDTO.setUserId(mapInfo.get("salesmanId").toString());
					}
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("userName", mapInfo.get("userName") == null ? "" : mapInfo.get("userName"));
					jsonObject.put("loginAccount", mapInfo.get("loginAccount"));
					jsonObject.put("orderNum", mapInfo.get("orderId"));
					jsonObject.put("carNum", form.getCarPlateNum());
					jsonObject.put("linkMan", form.getContactPerson() == null ? "" : form.getContactPerson());
					jsonObject.put("contactNum", form.getMobilePhone());
					sendDTO.setMsgContentParam(jsonObject);
					JSONObject jsonObjectJump = new JSONObject();
					jsonObjectJump.put("subOrderId", mapInfo.get("orderId"));
					jsonObjectJump.put("userId", mapInfo.get("userId"));// 业务员标识
					jsonObjectJump.put("orderPlat", mapInfo.get("orderSource"));
					sendDTO.setJumpData(jsonObjectJump);// 跳转参数设置
					xeSysMsgSendDTOList.add(sendDTO);
					msgRecordDTO.setXeSysMsgSendDTOList(xeSysMsgSendDTOList);
					log.info("批量派车成功向客户经理消消乐推送通知入参：--->" + JSON.toJSONString(msgRecordDTO));
					XeSysMsgRecordResDTO msgRecordResDTO = xeSysMsgApiService.sendMsgRecords(msgRecordDTO);
					log.info("批量派车成功向客户经理消消乐推送通知返回结果：--->" + JSON.toJSONString(msgRecordResDTO));

					// 派车向司机发短信
					String logtsCode = (String) mapInfo.get("logtsCode");
					String orderId = (String) mapInfo.get("orderId");
					String userCode = userInfo.getUserCode();
					String mobilePhone = form.getMobilePhone();

					log.info("-----PC端批量派车向司机发短信通知--------开始");
					weChatVenOrderLogisticsService.sendMsgToDriver(logtsCode, orderId, userCode, mobilePhone);
					log.info("-----PC端批量派车向司机发短信通知--------结束");

				}
				map.put("info", "派车成功！");

			} else {
				map.put("info", "保存失败，请稍后重试！");
			}
			return sendAjaxOK(map);
		} catch (Exception e) {
			log.error("保存批量派车信息接口异常：{}", e);
			return sendAjaxError();
		}

	}

	/**
	 * 查询车辆信息
	 *
	 * @author 赵盼飞
	 */
	@RequestMapping("queryCarList")
	public @ResponseBody BaseResponse queryCarList(@RequestBody XeVenOrderLogisticsForm form) {

		try {
			// 1.验证参数
			/*
			 * if(StringUtils.isEmpty(form.getProvinceId()) ||
			 * StringUtils.isEmpty(form.getCityId()) ||
			 * StringUtils.isEmpty(form.getAreaId()) ||
			 * StringUtils.isEmpty(form.getCaProvinceId()) ||
			 * StringUtils.isEmpty(form.getCaCityId()) ||
			 * StringUtils.isEmpty(form.getCaAreaId()) ||
			 * StringUtils.isEmpty(form.getLogtsCode())){ return
			 * sendAjaxError(BASEMessage.PARAM_ERROR); }
			 */
			if (StringUtils.isEmpty(form.getLogtsCode())) {
				return sendAjaxError(BASEMessage.PARAM_ERROR);
			}
			// 2.查询列表数据
			List<Map<String, Object>> sendCarLogisticsList = new ArrayList<Map<String, Object>>();
			// 查询当前区域的车辆，如果没有返回全部车辆
			sendCarLogisticsList = this.logisticsService.queryCarList(form);
			if (sendCarLogisticsList.size() <= 0) {
				sendCarLogisticsList = this.logisticsService.queryAllCarList(form);
			}
			// 3.返回分页信息
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("carList", sendCarLogisticsList);
			return sendAjaxOK(map);
		} catch (Exception e) {
			log.error("查询车辆信息接口异常：{}", e);
			return sendAjaxError();
		}

	}

	/**
	 * 批量派车查询车辆信息
	 *
	 * @author 赵盼飞
	 */
	@RequestMapping("queryBathCarList")
	public @ResponseBody BaseResponse queryBathCarList(@RequestBody XeVenOrderLogisticsForm form) {

		try {
			// 1.验证参数
			/*
			 * if(StringUtils.isEmpty(form.getProvinceId()) ||
			 * StringUtils.isEmpty(form.getCityId()) ||
			 * StringUtils.isEmpty(form.getAreaId()) ||
			 * StringUtils.isEmpty(form.getCaProvinceId()) ||
			 * StringUtils.isEmpty(form.getCaCityId()) ||
			 * StringUtils.isEmpty(form.getCaAreaId()) ||
			 * StringUtils.isEmpty(form.getLogtsCodeArr())){ return
			 * sendAjaxError(BASEMessage.PARAM_ERROR); }
			 */
			if (StringUtils.isEmpty(form.getLogtsCodeArr())) {
				return sendAjaxError(BASEMessage.PARAM_ERROR);
			}
			// 2.查询列表数据
			List<Map<String, Object>> sendCarLogisticsList = new ArrayList<Map<String, Object>>();
			// 查询当前区域的车辆，如果没有返回全部车辆
			sendCarLogisticsList = this.logisticsService.queryCarList(form);
			if (sendCarLogisticsList.size() <= 0) {
				sendCarLogisticsList = this.logisticsService.queryAllCarList(form);
			}
			// 3.返回分页信息
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("carList", sendCarLogisticsList);
			return sendAjaxOK(map);
		} catch (Exception e) {
			log.error("查询车辆信息接口异常：{}", e);
			return sendAjaxError();
		}

	}

	/**
	 * 新增车辆信息
	 *
	 * @author 赵盼飞
	 */
	@RequestMapping("saveCarInfo")
	public @ResponseBody BaseResponse saveCarInfo(@RequestBody XeVenCarForm form) {

		try {
			ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
			form.setUserCode(userInfo.getUserCode());
			// 1.验证参数
			if (StringUtils.isEmpty(form.getCarPlateNum()) || StringUtils.isEmpty(form.getMobilePhone())
					|| StringUtils.isEmpty(form.getProvinceId()) || StringUtils.isEmpty(form.getCityId())
					|| StringUtils.isEmpty(form.getAreaId()) || StringUtils.isEmpty(form.getCaProvinceId())
					|| StringUtils.isEmpty(form.getCaCityId()) || StringUtils.isEmpty(form.getCaAreaId())) {
				return sendAjaxError(BASEMessage.PARAM_ERROR);
			}
			// 2.验证车牌号是否存在
			form.setCarPlateNum(form.getCarPlateNum().toUpperCase());
			XeVenOrderLogisticsForm logisticsForm = new XeVenOrderLogisticsForm();
			logisticsForm.setCarPlateNum(form.getCarPlateNum());
			List<Map<String, Object>> sendCarLogistics = this.logisticsService.queryCarList(logisticsForm);
			if (sendCarLogistics.size() > 0) {
				return sendAjaxError(BASEMessage.PARAM_ERROR, XeVenLogisticsMsg.CAR_PLATENUM_EXISTENCE);
			}
			// 3.保存车辆信息
			int rs = logisticsService.saveCarInfo(form);
			Map<String, Object> map = new HashMap<String, Object>();
			if (rs > 0) {
				initLogisticsCar(JSONObject.parseObject(JSONObject.toJSONString(form), XeVenCarEntity.class));
				map.put("info", "新增车辆成功！");
				map.put("carId", form.getCarId());
			} else {
				map.put("info", "新增车辆失败！");
			}
			return sendAjaxOK(map);
		} catch (Exception e) {
			log.error("新增车辆信息接口异常：{}", e);
			return sendAjaxError();
		}

	}

	/**
	 * 跳转到修改派车页面
	 *
	 * @author 赵盼飞
	 */
	@RequestMapping("toUpdateSendCarPage")
	public @ResponseBody BaseResponse toUpdateSendCarPage(@RequestBody XeVenOrderLogisticsForm form,
			HttpServletRequest request) {

		try {
			// 1.验证参数
			if (StringUtils.isEmpty(form.getLogtsCode())) {
				return sendAjaxError(BASEMessage.PARAM_ERROR);
			}
			ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
			form.setUserCode(userInfo.getUserCode());
			// 2.查询列表数据
			Map<String, Object> sendCarLogistics = this.logisticsService.querySendCarLogisticsByLogtsCode(form);
			// 3.返回信息
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("sendCarLogistics", sendCarLogistics);
			return sendAjaxOK(map);
		} catch (Exception e) {
			log.error("跳转到修改派车页面接口异常：{}", e);
			return sendAjaxError();
		}

	}

	/**
	 * @param logType
	 *            操作类型
	 * @param key
	 *            单号
	 * @param operatorContent
	 *            操作内容 void
	 * @author 赵盼飞
	 */
	private void insertLogisticsMqLog(String logType, String key, String operatorContent) {
		try {
			String ipAddress = RequestUtil.getClientIpAddress(request);
			if (StringUtils.isEmpty(logType)) {
				logType = ErpLogTypeEnum.erpFinLogistics.getValue();
			}
			ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
			String userCode = userInfo.getUserCode();
			OpertorLogUtil.opertorLog.sendOperatorLogByParam(ipAddress, key, logType, userInfo.getUserName(),
					operatorContent, userCode);
		} catch (Exception e) {
			log.error("物流中心MQ日志插入失败,logType={},operatorContent={}", logType, operatorContent);
		}
	}

	/**
	 * 装车点，卸货点默认值，及历史记录
	 *
	 * @author 赵盼飞
	 */
	@RequestMapping("queryCarAddress")
	public @ResponseBody BaseResponse queryCarAddress(@RequestBody XeVenCarForm carForm, HttpServletRequest request) {

		try {
			// 1.验证参数
			// if(StringUtils.isEmpty(carForm.getCarId())){
			// return sendAjaxError(BASEMessage.PARAM_ERROR);
			// }

			// request.getSession().setAttribute("token", carForm.getToken());
			// log.info("存储session的token-----queryCarAddress----》》》"+request.getSession().getAttribute("token"));

			ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
			carForm.setUserCode(userInfo.getUserCode());
			// 2.查询列表数据
			List<Map<String, Object>> carAddressList = new ArrayList<Map<String, Object>>();
			Map<String, Object> carAddress = new HashMap<String, Object>();
			if (!StringUtils.isEmpty(carForm.getSelAddrFlag()) && carForm.getSelAddrFlag() == 1) {// 查询10条装车卸货历史记录
				carAddressList = this.logisticsService.queryCarAddressList(carForm);
			} else {
				carAddress = this.logisticsService.queryCarAddress(carForm);
			}
			// 3.返回信息
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("carAddressList", carAddressList);
			map.put("carAddress", carAddress);
			return sendAjaxOK(map);
		} catch (Exception e) {
			log.error("获取装车点，卸货点默认值，及历史记录接口异常：{}", e);
			return sendAjaxError();
		}

	}

	/**
	 * 初始化物流车辆
	 *
	 * @author xzd
	 */
	public void initLogisticsCar(XeVenCarEntity xeVenCarEntity) {

		log.info("=============== 初始化物流车辆 =============== start");
		try {
			xeLogisticsCarService.initLogisticsCar(xeVenCarEntity);
		} catch (Exception e) {
			log.error("初始化物流车辆异常", e);
		}
	}

	/**
	 * 确认接货
	 *
	 * @author 袁世林
	 */
	@RequestMapping("confirmDelivery")
	public BaseResponse confirmDelivery(@RequestBody XeVenOrderLogisticsForm form) {

		String paramJson = JSONObject.toJSONString(form);
		log.info("确认接货,传入参数： {}", paramJson);
		try {
			if (StringUtils.isEmpty(form.getLogtsCode())) {
				return sendAjaxError(BASEMessage.PARAM_ERROR);
			}
			weChatVenOrderLogisticsService.confirmDelivery(form.getLogtsCode());

			ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
			// 添加操作日志信息
			OpertorLogUtil.opertorLog.sendOperatorLogByParam(getRequestIP(), null,
					ErpLogTypeEnum.erpFinLogistics.getValue(), userInfo.getLoginName(),
					"PC端生意管家---物流单号: " + form.getLogtsCode() + "--确认接货成功", userInfo.getUserCode());

			return sendAjaxOK();
		} catch (Exception e) {
			log.error("确认接货 接口异常：{}", e);
			return sendAjaxError(BASEMessage.PARAM_ERROR);
		}

	}

}